﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Medianamik.Core.DAL.SQL
{
    public class NumericExpression : IExpression
    {
        public object NumericValue
        {
            get; private set;
        }
        public NumericExpression(object value)
        {
            ValidateParameter(value);
            NumericValue = value;
        }

        private void ValidateParameter(object value)
        {
            double d;
            if(value == null)
            {
                throw new ArgumentNullException("value"); 
            }
            if(value is IConvertible)
            {
                switch (((IConvertible)value).GetTypeCode()  )
                {
                    case TypeCode.Boolean:
                    case TypeCode.SByte:
                    case TypeCode.Byte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                    case TypeCode.Single:
                    case TypeCode.Double:
                    case TypeCode.Decimal:
                        break;
                    default:
                        throw new ArgumentException("value must be numeric", "value");
                        
                }
            }
            else if(!double.TryParse(value.ToString(),out d ))
            {
                throw new ArgumentException("value must be numeric","value"); 
            }
        }

        #region ISqlQueryPart Members

        public StringBuilder ToSQL()
        {
            return new StringBuilder(FormatValue(NumericValue));
        }

        public string FormatValue(object value)
        {
            if(value is bool)
            {
                return ((bool) value) ? "1" : "0";
            }
            return value.ToString();
        }

        #endregion
    }
}
